package com.sxhuayuan.parking.utils;

import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

public class RSAKeyUtil {

	/**
	 * 生成密钥对
	 * 
	 * @return
	 * @throws Exception
	 */
	public static KeyPair generateKey() throws Exception {
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		keyPairGen.initialize(1024);
		KeyPair keyPair = keyPairGen.generateKeyPair();
		return keyPair;
	}

	/**
	 * 保存到文件
	 * 
	 * @param path
	 * @param y
	 * @throws Exception
	 */
	public static void saveFile(String path, String key) throws Exception {
		FileOutputStream fos = new FileOutputStream(path);
		fos.write(key.getBytes());
		fos.flush();
		fos.close();
	}

	/**
	 * @param args
	 * @throws Exception
	 */
	// public static void main(String[] args) throws Exception {
	// KeyPair keyPair = generateKey();
	// // 私钥
	// PrivateKey privateKey = keyPair.getPrivate();
	// byte[] privateBT = privateKey.getEncoded();
	//
	// String prk = Base64.encodeBase64String(privateBT);
	// System.out.println("private=[" + prk + "]");
	// System.out.println("private=[" + RSAUtils.getKeyString(privateKey) +
	// "]");
	// // base64
	// // saveFile("d://privateKey.txt", Base64.encodeBase64String(privateBT));
	// // ============================================//
	// // 公钥
	// PublicKey publicKey = keyPair.getPublic();
	// byte[] publicBT = publicKey.getEncoded();
	// // base64
	// // saveFile("d://publicKey.txt", Base64.encodeBase64String(publicBT));
	// String puk = Base64.encodeBase64String(publicBT);
	// System.out.println("public=[" + puk + "]");
	// System.out.println("public=[" + RSAUtils.getKeyString(publicKey) + "]");
	// String psw = "123123";
	//
	// String enPsw = RSAUtils.encryptByPublicKey(psw, puk);
	// System.out.println("加密文=" + enPsw);
	//
	// System.out.println("解密文=" + RSAUtils.decrypt(prk, enPsw));
	// }

	public static void main(String[] args) throws Exception {
		testRsa();
		// testDecrypt("Tb8psxmMkZ1V7gQEr0+cFR2bsA1H9bD39Km74k6uGL9gzSFgIaqhTmt/A5Y93yQK2PNGjXkuW1SPAAQmiNZdFw==");
	}

	static String prk = "MIICdg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QAB";
	static String puk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNL1Px70vEulU/KY8BMPew2/lYQWwS2KvkGCK58GYnP2WqaqkC6EqChur1Feqcmq2VRoS0D5yfGhv94YdZ6RppNxPmSPeDbS1bQ0vmnBkuUyFt/I8jKhPNSZQC+KRpRjPQvG21jlqfwXIOhQOtQSZeC8uKxCbEaT+YE8ETjO2iCQIDAQAB";

	public static void testRsa() throws Exception {
		//
		// String psw = "123123";
		//
		// String enPsw = RSAUtils.encryptByPublicKey(psw, puk);
		// System.out.println("加密文=" + enPsw);

		System.out.println("解密文=" + RSAUtils.decrypt(prk,
				"d3W4EdD8ga+giac4yVBjk2sbh12I2hnDZ6T9XzaX46/iUvJ6KF6U0ZEEc7msh7YYxQbaSsDKSBVEhEsDLCCH/pL0WmAlKesXkcewQMfXKliiAekYk0Pii1EI3rwfzUz+Fpuu+5j/nELrBPlOeJVOVuPd1Odc4Jl7J/CAZCMPPWM="));
	}

	public static void testDecrypt(String enPsw) throws Exception {
		System.out.println("解密文=" + RSAUtils.decrypt(prk, enPsw));
	}
}